<?php

namespace Addons\Oss;

use Common\Controller\Addon;

class OssAddon extends Addon
{
    public $info = array(
        'name' => 'Oss',
        'title' => '阿里云存储 oss 2017版',
        'description' => '阿里云存储 2017新版',
        'status' => 1,
        'author' => '卡卡',
        'version' => '1.8.0'
    );

    public function install()
    {
        return true;
    }

    public function uninstall()
    {
        return true;
    }

    /**
     * uploadDriver  上传驱动，必需，用于确定插件是否是上传驱动
     * @return bool
     * @author:xjw129xjt(肖骏涛) xjt@ourstu.com
     */
    public function uploadDriver()
    {
        return true;
    }

    /**
     * uploadConfig   获取上传驱动的配置
     * @return array
     * @author:xjw129xjt(肖骏涛) xjt@ourstu.com
     */
    public function uploadConfig()
    {
        $config = $this->getConfig();
        return $uploadConfig = array(
            'access_id' => $config['access_id'],
            'access_key' => $config['access_key'],
            'bucket' => $config['bucket'],
            'oss_host' => $config['oss_host'],
            'bind_host' => $config['bind_host'],
            'timeout' => 3600,
        );
    }


    /**
     * uploadDealFile   处理上传参数
     * @param $file
     * @author:xjw129xjt(肖骏涛) xjt@ourstu.com
     */
    public function uploadDealFile(&$file)
    {

    }

    /**
     * crop  裁剪图片  [新版]
     */
//    public function crop($path, $crop)
//    {
//        //解析crop参数
//        $crop = explode(',', $crop);
//        $x_ratio = $crop[0];
//        $y_ratio = $crop[1];
//        $width_ratio = $crop[2];
//        $height_ratio = $crop[3];
//
//        $imageInfo = getimagesize($path);
//
//        //生成将单位换算成为像素
//        $x = round($x_ratio * $imageInfo[0]);
//        $y = round($y_ratio * $imageInfo[1]);
//        $width = round($width_ratio * $imageInfo[0]);
//        $height = round($height_ratio * $imageInfo[1]);
//        $suffix = '?x-oss-process=image/crop,x_'.$x.',y_'.$y.',w_'.$width.',h_'.$height;
//
//        //返回新文件的路径
//        return $path . $suffix;
//    }

    /**
     * thumb  取缩略图
     */
    public function thumb($path, $w = 260, $h = 260, $isPipe = false)
    {
        if ($w == 'auto' || $h == 'auto') {
            $suffix = '';
        } else {
//            $conSign = $isPipe ? '|' : '@';
            $conSign = (strrpos($path, '@') === false) ? '@' : '|';
            $suffix = $conSign . $h . 'h_' . $w . 'w_0e';
        }
        return $path . $suffix;
//        $suffix = '?x-oss-process=image/resize,m_lfit,h_' . $height . ',w_' . $width;  // 新版
//        return $path . $suffix;
    }

    /**
     * crop  裁剪图片
     * @param $path
     * @param $crop
     * @return string
     * @author:xjw129xjt(肖骏涛) xjt@ourstu.com
     */
    public function crop($path, $crop)
    {
        //解析crop参数
        $crop = explode(',', $crop);
        $x = $crop[0];
        $y = $crop[1];
        $width = $crop[2];
        $height = $crop[3];

        $imageInfo = getimagesize($path);

        //生成将单位换算成为像素
        $x = round($x * $imageInfo[0]);
        $y = round($y * $imageInfo[1]);
        $width = round($width * $imageInfo[0]);
        $height = round($height * $imageInfo[1]);

        $new_img = $path . '@' . $x . '-' . $y . '-' . $width . '-' . $height . 'a';
        //返回新文件的路径
        return $new_img;
    }

    /**
     * thumb  取缩略图
     * @param $path
     * @param string $width
     * @param string $height
     * @return string
     * @author:xjw129xjt(肖骏涛) xjt@ourstu.com
     */
    // 根据宽高强行缩放 /实测会被裁剪
//    public function thumb($path, $width = '', $height = '')
//    {
//        if (stripos($path, '@') === false) {
//            $path .= '@' . $width . 'w_' . $height . 'h_1c_1e';
//        } else {
//            $path .= '_' . $width . 'w_' . $height . 'h_1c_1e';
//        }
//        return $path;
//    }


    public function uploadRemote($url, $savePath)
    {
        $config = $this->uploadConfig();
        $resource = fopen($url, 'r');
        $file = curl_get_headers($url);
        $_headers = array('Content-Type: ' . $file['Content-Type']);
        $uri = "/{$config['bucket']}/{$savePath}";
        if (stripos($file['Content-Type'], 'image') === false) {
            $return = 'http://' . $config['oss_host'] . '.aliyuncs.com' . $uri;
        } else {
            $return = 'http://' . $config['bind_host'] . '/' . $savePath;
        }
        $ch = curl_init('http://' . $config['oss_host'] . '.aliyuncs.com' . $uri);
        $date = gmdate('D, d M Y H:i:s \G\M\T');
        array_push($_headers, "Date: {$date}");
        $sign_string = "PUT\n\n" . $file['Content-Type'] . "\n" . $date . "\n" . $uri;
        $sign = $this->hex_to_base64(hash_hmac('sha1', $sign_string, $config['access_key']));
        array_push($_headers, 'Authorization: OSS ' . $config['access_id'] . ':' . $sign);

        array_push($_headers, "Content-Length: {$file['Content-Length']}");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_INFILE, $resource);
        curl_setopt($ch, CURLOPT_INFILESIZE, $file['Content-Length']);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $_headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, $config['timeout']);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        $response = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        fclose($resource);
        if ($status == 200) {
            return $return;
        } else {
            return false;
        }
    }

    private function hex_to_base64($str)
    {
        $result = '';

        for ($i = 0; $i < strlen($str); $i += 2) {
            $result .= chr(hexdec(substr($str, $i, 2)));
        }

        return base64_encode($result);
    }


    public function uploadBase64($base64, $savePath)
    {
        $ext = end(explode('.',$savePath));
        $data  = base64_decode($base64);
        $config = $this->uploadConfig();
        $content_type = 'image/'.$ext;
        $uri = "/{$config['bucket']}{$savePath}";
        $return = 'http://' . $config['bind_host'] . $savePath;
        $_headers = array('Content-Type: ' . $content_type);
        $date = gmdate('D, d M Y H:i:s \G\M\T');
        array_push($_headers, "Date: {$date}");
        $sign_string = "PUT\n\n" . $content_type . "\n" . $date . "\n" . $uri;
        $sign = $this->hex_to_base64(hash_hmac('sha1', $sign_string, $config['access_key']));
        array_push($_headers, 'Authorization: OSS ' . $config['access_id'] . ':' . $sign);
        //dump(strlen($data));
        array_push($_headers, "Content-Length: ".strlen($data));

        array_push($_headers, "Content-Disposition: ".$savePath);
        array_push($_headers, "Content-Encoding: utf-8 ");
        array_push($_headers, "Cache-control: no-cache");

        $curl = curl_init('http://' . $config['oss_host'] . '.aliyuncs.com' . $uri);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $_headers);
        curl_setopt($curl, CURLOPT_TIMEOUT, $config['timeout']);
        curl_setopt($curl, CURLOPT_HEADER, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        $con = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($status == 200) {
            return $return;
        } else {
            return false;
        }

    }


}